package LinkedList;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 86138
 * Date: 2024-07-27
 * Time: 18:08
 */
public class LinkedList implements IList{
    class LinkedNode{
        public int val;
        public LinkedNode pre;
        public LinkedNode next;

        LinkedNode(int val) {
            this.val = val;
        }
    }

    public LinkedNode head;
    public LinkedNode last;
    //头插法
    public void addFirst(int data){
        LinkedNode node = new LinkedNode(data);
        if(head == null){
            head = last = node;
        }else{
            node.next = head;
            head.pre = node;
            head = node;
        }
    }
    //尾插法
    public void addLast(int data){
        LinkedNode node = new LinkedNode(data);
        if(head == null){
            head = last = node;
        }else{
            last.next = node;
            node.pre = last;
            last = last.next;
        }
    }
    //任意位置插入,第一个数据节点为0号下标
    public void addIndex(int index,int data){
        int len = size();
        if(len == 0 || index>len){
            return;
        }
        if(index == 0){
            addFirst(data);
            return;
        }
        if(index == len){
            addLast(data);
            return;
        }
        LinkedNode cur = head;
        LinkedNode node = new LinkedNode(data);
        while (index!=0){
            cur = cur.next;
            index--;
        }
        node.next = cur;
        node.pre = cur.pre;
        cur.pre.next = node;
        cur.pre = node;
    }
    //查找是否包含关键字key是否在单链表当中
    public boolean contains(int key){
        LinkedNode cur = head;
        while (cur!=null){
            if(cur.val == key){
                return  true;
            }
            cur = cur.next;
        }
        return false;
    }
    //删除第一次出现关键字为key的节点
    public void remove(int key){

    }
    //删除所有值为key的节点
    public void removeAllKey(int key){

    }
    //得到单链表的长度
    public int size(){
        int len = 0;
        LinkedNode cur = head;
        while (cur!=null){
            len++;
            cur = cur.next;
        }
        return len;
    }
    public void clear(){

    }
    public void display(){
        LinkedNode cur = head;
        while (cur!=null){
            System.out.print(cur.val + " ");
            cur = cur.next;
        }
    }
}
